<script lang="ts" setup>
import { onMounted, ref } from "vue";

import {
  getShangData,
  addShangData,
  getShangType,
  delShangData,
  getShangId,
  editShangData,
  setDanData,
  setShangData,
  setJingData,
  setUpData
} from "../../api/shang";

//获取数据
let data = ref([]);
const total = ref("");
let fenlie = ref<any>([]);
onMounted(() => {
  get();
  getShangType().then((res: any) => {
    fenlie.value = Object.values(res);
  });
});

function get() {
  getShangData(currentPage4.value, pageSize4.value).then((res: any) => {
    data.value = Object.values(res.data.data);

    total.value = res.data.total;
  });
}

// 表格
let dialogVisible = ref(false);
let flag = ref(true);

//图片
import { Plus } from "@element-plus/icons-vue";

const imageUrl = ref("");

let handleAvat = (e: any) => {
  let filedata = e.raw;
 
  // 创建fliereader对象

  const reader = new FileReader();
  reader.onload = () => {
    imageUrl.value = reader.result as string;
    useFrom.value.img_path = reader.result as string;
  };
  reader.readAsDataURL(filedata);
  useFrom.value.img_path = filedata;

};

//规格
import { nextTick } from "vue";
import { ElInput } from "element-plus";

const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  useFrom.value.specification.splice(
    useFrom.value.specification.indexOf(tag),
    1
  );
};.967410

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    useFrom.value.specification.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

//轮播图

import type { UploadProps, UploadUserFile } from "element-plus";

const fileList = ref<UploadUserFile[]>([]);

const dialogImageUrl = ref("");
const dialogVisibl = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisibl.value = true;
};

const addchange = (e:any) => {
  let filedata = e.raw;

  // 创建fliereader对象

  const reader = new FileReader();
  reader.onload = () => {
    useFrom.value.img_arr.push(reader.result as string);
  };
  reader.readAsDataURL(filedata);
};

// 分页
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const handleSizeChange = (val: number) => {
  get();
};
const handleCurrentChange = (val: number) => {
  get();
};




interface usefrom {
  is_danpin: number;
  is_shangxin: number;
  is_jingxuan: number;
  name: string;
  category_id: number;
  describe: string;
  img_path: string;
  img_arr: string[];
  price: number;
  repertory: number;
  market: number;
  sales_volume: number;
  content: string;
  specification: string[];
  is_shangjia:number
}

let useFrom = ref<usefrom>({
  is_danpin: 1,
  is_shangxin: 1,
  is_jingxuan: 1,
  name: "",
  category_id: 0,
  describe: "",
  img_path: "",
  img_arr: [],
  price: 0,
  repertory: 0,
  market: 0,
  sales_volume: 0,
  content: "",
  specification: [],
  is_shangjia:1
});
let tian = () => {
  dialogVisible.value = true;
  flag.value = true;
};
// 添加
let add = () => {
  if (flag.value) {
    addShangData(useFrom.value).then((res) => {
     console.log(res);
      get();

      dialogVisible.value = false;

      useFrom.value = {
        is_danpin: 1,
        is_shangxin: 1,
        is_jingxuan: 1,
        name: "",
        category_id: 0,
        describe: "",
        img_path: "",
        img_arr: [],
        price: 0,
        repertory: 0,
        market: 0,
        sales_volume: 0,
        content: "",
        specification: [],
        is_shangjia:1
      };

      // fileList.value = [];
    });
  } else {
    editShangData(useFrom.value).then((res: any) => {
      // console.log(res);

      get();
      dialogVisible.value = false;

      useFrom.value = {
        is_danpin: 1,
        is_shangxin: 1,
        is_jingxuan: 1,
        name: "",
        category_id: 0,
        describe: "",
        img_path: "",
        img_arr: [],
        price: 0,
        repertory: 0,
        market: 0,
        sales_volume: 0,
        content: "",
        specification: [],
        is_shangjia:1
      };
    });
  }
};

//删除功能
const handleDelete = (index: number, row: any) => {
  delShangData(row.id).then((res: any) => {
    get();
    dialogVisible.value = false;
  });
};

//回显功能
const handleEdit = (index: number, row: any) => {
  flag.value = false;
  dialogVisible.value = true;

  getShangId(row.id).then((res: any) => {
    useFrom.value = {
      is_danpin: res.is_danpin,
      is_shangxin: res.is_shangxin,
      is_jingxuan: res.is_jingxuan,
      name: res.name,
      category_id: res.category_id,
      describe: res.describe,
      img_path: res.img_path,
      img_arr: res.img_arr,
      price: res.price,
      repertory: res.repertory,
      market: res.market,
      sales_volume: res.sales_volume,
      content: res.content,
      specification: Object.values(res.specification),
      id: res.id,
      is_shangjia:res.is_shangjia
    };
    imageUrl.value = res.img_path;
    let obj = Object.values(res.img_arr);
    fileList.value = [];
    useFrom.value.img_arr = Object.values(res.img_arr);
    obj.forEach((item) => {
      fileList.value.push({
        name: item,
        url: item,
      });
    });
  });
};

import {useRouter} from 'vue-router'
let router = useRouter()


//设置规格
let handleDelets=(id:number,data:any)=>{

  router.push(`/sku?id=${data.id}`)


}


//单品功能
let danpinChange=(index:number,row:any)=>{
  setDanData(row).then((res:any)=>{
      get()
  })
}



//上新问题
let shangxinChange=(index:number,row:any)=>{
  setShangData(row).then((res:any)=>{
      get()
  })
}

//精选问题
let youxuanChange=(index:number,row:any)=>{
  setJingData(row).then((res:any)=>{
      get()
  })
}

//上下架
let shangjiaChange=(index:number,row:any)=>{
  
  setUpData(row).then((res:any)=>{
    console.log(res);
    
      get()
  })
}








</script>
<template>
  <!-- 添加商品 -->
  <div>
    <el-button @click="tian">添加商品</el-button>
  </div>

  <!-- 表格 -->
  <el-table :data="data" style="width: 100%">
    <el-table-column label="商品名称" prop="name" />
    <el-table-column label="商品分类" prop="category_id" />
    <el-table-column label="商品图片" prop="img" #default="scope">
      <img :src="scope.row.img_path" alt="" style="width: 100px; height: 100px;"
    </el-table-column>
    <el-table-column label="商品价格" prop="price" />
    <el-table-column label="商品库存" prop="repertory" />

    <el-table-column label="是否热销单品" prop="danpin" #default="scope">
      <el-switch
        v-model="scope.row.is_danpin"
        :active-value="2"
        :inactive-value="1"
        @change="danpinChange(scope.$index, scope.row)"
      />

    </el-table-column>

    <el-table-column label="是否热销上新" prop="shangxin" #default="scope">
      <el-switch
        v-model="scope.row.is_shangxin"
        :active-value="2"
        :inactive-value="1"
        @change="shangxinChange(scope.$index, scope.row)"
       
      />
    </el-table-column>
    <el-table-column label="是否热销优选" prop="youxuan" #default="scope">
      <el-switch
        v-model="scope.row.is_jingxuan"
        :active-value="2"
        :inactive-value="1"
        @change="youxuanChange(scope.$index, scope.row)"
      />
    </el-table-column>

    <el-table-column label="是否上下架" prop="youxuan" #default="scope">
      <el-switch
        v-model="scope.row.is_shangjia"
        :active-value="1"
        :inactive-value="2"
        @change="shangjiaChange(scope.$index, scope.row)"
      />
    </el-table-column>

    <el-table-column align="right" label="操作" style="width: 300px;" >
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
          >修改</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelets(scope.$index, scope.row)"
          >设置规格</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加弹框 -->
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="flag == true ? '添加商品' : '修改商品'"
      width="800"
    >
      <span>
        <!-- 名称 -->
        <div>
          套装名称:<el-input
            placeholder="请输入排序号"
            style="width: 650px"
            v-model="useFrom.name"
          />
        </div>

        <!-- 分类 -->
        <div>
          套装分类：
          <el-select
            v-model="useFrom.category_id"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in fenlie"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </div>

        <!-- 描述 -->
        <div>
          描述：
          <el-input
            v-model="useFrom.describe"
            style="width: 240px"
            :rows="2"
            type="textarea"
            placeholder="Please input"
          />
        </div>

        <!-- 图片 -->
        <div>
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            @change="handleAvat($event)"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100px; height: 100px;"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>

        <!-- 轮播图 -->
        <div>
          <el-upload
            v-model:file-list="fileList"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            list-type="picture-card"
            :auto-upload="false"
            @change="addchange"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisibl">
            <img w-full :src="dialogImageUrl" alt="Preview Image"  style="width: 100px; height: 100px;"/>
          </el-dialog>
        </div>

        <!-- 价格 -->
        <div>
          价格：
          <el-input
            v-model="useFrom.price"
            style="width: 240px"
            placeholder="Please input"
            :formatter="(value:any) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="(value:any) => value.replace(/\$\s?|(,*)/g, '')"
          />
        </div>

        <!-- 库存 -->
        <div>
          库存:
          <el-input
            v-model="useFrom.repertory"
            style="width: 240px"
            placeholder="Please input"
          />
        </div>

        <!-- 市场价 -->
        <div>
          市场价:
          <el-input
            v-model="useFrom.market"
            style="width: 240px"
            placeholder="Please input"
            :formatter="(value:any) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="(value:any) => value.replace(/\$\s?|(,*)/g, '')"
          />
        </div>

        <!-- 虚拟销量 -->
        <div>
          虚拟销量:
          <el-input
            v-model="useFrom.sales_volume"
            style="width: 240px"
            placeholder="Please input"
          />
        </div>

        <!-- 详情  -->
        <div>
          <div style="border: 1px solid #ccc">
            <div class="editor">
              <quill-editor
                content-type="html"
                v-model:content="useFrom.content"
                style="width: 100%; height: 400px"
                toolbar="full"
              >
              </quill-editor>
            </div>
          </div>
        </div>

        <div class="flex gap-2">
          <el-tag
            v-for="tag in useFrom.specification"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >
            + New Tag
          </el-button>
        </div>

        <!-- 是否热销单品 -->
        <div>
          是否热销单品:
          <el-switch
            v-model="useFrom.is_danpin"
            :active-value="2"
            :inactive-value="1"
          />
        </div>

        <!-- 是否今日上新 -->
        <div>
          是否今日上新:
          <el-switch
            v-model="useFrom.is_shangxin"
            :active-value="2"
            :inactive-value="1"
          />
        </div>

        <!-- 是否精品优选 -->
        <div>
          是否精品优选:
          <el-switch
            v-model="useFrom.is_jingxuan"
            :active-value="2"
            :inactive-value="1"
          />
        </div>
        <div>
          是否上下架:
          <el-switch
            v-model="useFrom.is_shangjia"
            :active-value="2"
            :inactive-value="1"
          />
        </div>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="add"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <div class="demonstration">All combined</div>
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style lang="less" scoped>

*{
  margin: 0;
  padding: 0;

}
.el-table__header-wrapper{
  margin: 0 auto;
}



</style>
